package com.zHan.interceptor;

import com.zHan.utils.JwtUtil;
import com.zHan.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * ClassName: LoginInception
 * Description:
 * date: 2023/11/8 0008 0:22
 *
 * @author zHan
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取jwt令牌
        String token = request.getHeader("Authorization");
        try {
            // 解析jwt令牌
            Map<String, Object> claims = JwtUtil.parseToken(token);

            // 将解析的jwt令牌存入ThreadLocal
            ThreadLocalUtil.set(claims);

            // 从redis中获取token
            String redisToken = stringRedisTemplate.opsForValue().get(token);
            if (redisToken == null) {
                throw new RuntimeException();
            }

            // 放行
            return true;
        } catch (Exception e) {
            // 设置响应状态码为401
            response.setStatus(401);
            // 拦截
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        // 清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
